<script lang="ts">
import { useI18n } from 'vue-i18n'

export default {
	name: 'CurrencySwitch',

	data() {
		return {
			currencies: []
		}
	},

	setup() {
		const currencyStore = useCurrencyStore()
		const { t } = useI18n()
		const { currentCurrency } = storeToRefs(currencyStore)
		return {
			currencyStore,
			t,
			currentCurrency
		}
	},

	mounted() {
		this.updateCurrencyLabels()
	},

	methods: {
		updateCurrencyLabels() {
			this.currencies = [
				{ key: 'CNY', label: this.t('货币.人民币'), symbol: '¥' },
				{ key: 'USD', label: this.t('货币.美元'), symbol: '$' },
				{ key: 'RUB', label: this.t('货币.卢布'), symbol: '₽' }
			]
		},

		handleCurrencyChange(currency: string) {
			this.currencyStore.setCurrency(currency as 'CNY' | 'USD' | 'RUB')
			this.updateCurrencyLabels()
		},

		getCurrentCurrencySymbol(currency: string) {
			const curr = this.currencies.find(c => c.key === currency)
			return curr ? curr.symbol : '¥'
		},

		getCurrentCurrencyLabel(currency: string) {
			const curr = this.currencies.find(c => c.key === currency)
			return curr ? curr.label : this.t('货币.人民币')
		}
	},

	watch: {
		currentCurrency: {
			handler() {
				this.updateCurrencyLabels()
			},
			immediate: true
		},
		// 监听语言变化，更新货币显示名称
		'$i18n.locale': {
			handler() {
				this.updateCurrencyLabels()
			},
			immediate: true
		}
	}
}
</script>

<template>
	<a-dropdown :trigger="['click']" placement="bottomRight">
		<a-button type="text" class="currency-switch">
			<span class="mr-1">{{ getCurrentCurrencySymbol(currentCurrency) }}</span>
			<span>
				{{ getCurrentCurrencyLabel(currentCurrency) }}
			</span>
		</a-button>
		<template v-slot:overlay>
			<a-menu>
				<a-menu-item
					v-for="currency in currencies"
					:key="currency.key"
					@click="handleCurrencyChange(currency.key)"
					:class="{ 'ant-menu-item-selected': currentCurrency === currency.key }">
					<span class="mr-2">{{ currency.symbol }}</span>
					<span>{{ currency.label }}</span>
				</a-menu-item>
			</a-menu>
		</template>
	</a-dropdown>
</template>

<style scoped>
.currency-switch {
	color: inherit;
}
.currency-switch:hover {
	color: #1890ff;
}
</style>
